package cn.com.gas.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasCamchangeEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.service.GasCamchangeService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.HmacSha256Utils;
import cn.com.util.HttpUtils;
import cn.com.util.MD5Utils;
import cn.com.util.TsBqUtils;

/**
 * 摄像头变动
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2024-09-25 21:07:25
 */
@Controller
@RequestMapping("/gas/camchange")
@Slf4j
public class GasCamchangeController {
	@Autowired
	private GasCamchangeService gasCamchangeService;
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private HttpSessionService httpSessionService;
	@Value("${gasstation.thirdPartyPass}")
	private String pass;
	@Value("${gasstation.thirdPartyUser}")
	private String user;

	@Value("${gasstation.configCamAIAnalyseSceneChangeAckUrl}")
	private String url;

	@ApiOperation(value = "更新")
	@PutMapping("/update")
	@ResponseBody
	public DataResult update(@RequestBody GasCamchangeEntity gasCamchange) throws Exception {

		String currentUserId = httpSessionService.getCurrentUserId();
		String handleType = gasCamchange.getHandleType();
		String handleReason = gasCamchange.getHandleReason();

		String id = gasCamchange.getId();
		GasCamchangeEntity gasCamchangeEntity = gasCamchangeService.getById(id);

		if (TsBqUtils.isNull(handleType)) {
			return DataResult.fail("处理类型未选择！");
		}

		if (TsBqUtils.isNull(handleReason)) {
			return DataResult.fail("原因未填写！");
		}

		gasCamchangeEntity.setHandleType(handleType);
		gasCamchangeEntity.setHandleReason(handleReason);

		gasCamchangeEntity.setUpdateId(currentUserId);
		gasCamchangeEntity.setUpdateTime(new Date());
		gasCamchangeService.updateById(gasCamchangeEntity);
		// 反馈到底层

		/*
		 * camerainfo=[{"camid":206627,"groupid":
		 * "07f23824-bb9a-471f-9219-19f708db0679","acked":1}]
		 */
		
		List<Map<String, Object>> listmap = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		map.put("camid", Integer.valueOf(gasCamchangeEntity.getMessageCamid()));
		map.put("groupid", gasCamchangeEntity.getMessageGroupid());
		map.put("acked", 1);
		listmap.add(map);
		String jsonString = JSON.toJSONString(listmap);
		log.info("GasCamchange请求报文："+jsonString);
		String _url = url+"?api="+user+"&sign=OEgPWMjS1dBkepHXG9BkbpE4PFJZxGoNDpO%2BTC%2BBLTQ%3D";
		log.info("GasCamchange请求URL："+_url);
		String doPost = HttpUtils.doPost(_url, jsonString);
		log.info("GasCamchange请求结果res:" + doPost);
		return DataResult.success();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据(未处理)")
	@PostMapping("/list1")
	@ResponseBody
	public DataResult list1(@RequestBody GasCamchangeEntity gasCamchange) throws ParseException {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String currentDeptId = httpSessionService.getCurrentDeptId();
		String taxorgcode = gasCamchange.getTaxorgcode();

		String stationinfoName = gasCamchange.getStationinfoName();
		List<String> stationinfoIdList = new ArrayList<>();
		
		LambdaQueryWrapper<GasStationinfoEntity> queryStationinfo = Wrappers.lambdaQuery();
		queryStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
		queryStationinfo.eq(GasStationinfoEntity::getType, "group");
		if (TsBqUtils.isNotNull(stationinfoName)) {
			queryStationinfo.like(GasStationinfoEntity::getName, stationinfoName);
		}
		List<GasStationinfoEntity> list = gasStationinfoService.list(queryStationinfo);
		if (TsBqUtils.isNotNull(list)) {
			for (GasStationinfoEntity stationinfo : list) {
				String id = stationinfo.getId();
				stationinfoIdList.add(id);
			}
		} else {
			return DataResult.fail("未查询到加油站！");
		}
		

		String createTimeStart = gasCamchange.getCreateTimeStart();
		String createTimeEnd = gasCamchange.getCreateTimeEnd();
		// String stationinfoName = gasCamchange.getStationinfoName();

		Page page = new Page(gasCamchange.getPage(), gasCamchange.getLimit());
		LambdaQueryWrapper<GasCamchangeEntity> queryWrapper = Wrappers.lambdaQuery();
		// 查询条件示例
		if (!StringUtils.isEmpty(createTimeStart)) {
			queryWrapper.ge(GasCamchangeEntity::getCreateTime, sdf.parse(createTimeStart + " 00:00:00"));
		}
		if (!StringUtils.isEmpty(createTimeEnd)) {
			queryWrapper.le(GasCamchangeEntity::getCreateTime, sdf.parse(createTimeEnd + " 23:59:59"));
		}

		if (!StringUtils.isEmpty(taxorgcode)) {
			queryWrapper.eq(GasCamchangeEntity::getHandleTaxorgcode, taxorgcode);

		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapper.eq(GasCamchangeEntity::getHandleTaxorgcode, currentDeptId);
			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局
				queryWrapper.like(GasCamchangeEntity::getHandleTaxorgcode, currentDeptId.substring(0, 5));
			} else {
				// 省局
			}
		}

		if (TsBqUtils.isNotNull(stationinfoIdList)) {
			queryWrapper.in(GasCamchangeEntity::getMessageGroupid, stationinfoIdList);
		}

		queryWrapper.isNull(GasCamchangeEntity::getHandleType);

		IPage<GasCamchangeEntity> iPage = gasCamchangeService.page(page, queryWrapper);
		List<GasCamchangeEntity> records = iPage.getRecords();
		for (GasCamchangeEntity camchangeEntity : records) {
			String messageGroupid = camchangeEntity.getMessageGroupid();
			GasStationinfoEntity stationinfoEntity = gasStationinfoService.getById(messageGroupid);
			if (TsBqUtils.isNotNull(stationinfoEntity)) {
				String name = stationinfoEntity.getName();
				camchangeEntity.setStationinfoName(name);
				String taxpayerCode = stationinfoEntity.getTaxpayerCode();
				camchangeEntity.setTaxpayerCode(taxpayerCode);
			}

		}

		return DataResult.success(iPage);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据(已处理)")
	@PostMapping("/list2")
	@ResponseBody
	public DataResult list2(@RequestBody GasCamchangeEntity gasCamchange) throws ParseException {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String currentDeptId = httpSessionService.getCurrentDeptId();
		String taxorgcode = gasCamchange.getTaxorgcode();
		String stationinfoName = gasCamchange.getStationinfoName();
		List<String> stationinfoIdList = new ArrayList<>();
			
		LambdaQueryWrapper<GasStationinfoEntity> queryStationinfo = Wrappers.lambdaQuery();
		
		queryStationinfo.eq(GasStationinfoEntity::getIsAnalyse, "Y");
		queryStationinfo.eq(GasStationinfoEntity::getType, "group");
		if (TsBqUtils.isNotNull(stationinfoName)) {
			queryStationinfo.like(GasStationinfoEntity::getName, stationinfoName);
		}
		
		queryStationinfo.like(GasStationinfoEntity::getName, stationinfoName);
		List<GasStationinfoEntity> list = gasStationinfoService.list(queryStationinfo);
		if (TsBqUtils.isNotNull(list)) {
			for (GasStationinfoEntity stationinfo : list) {
				String id = stationinfo.getId();
				stationinfoIdList.add(id);
			}
		} else {
			return DataResult.fail("未查询到加油站！");
		}
		
		String createTimeStart = gasCamchange.getCreateTimeStart();
		String createTimeEnd = gasCamchange.getCreateTimeEnd();
		// String stationinfoName = gasCamchange.getStationinfoName();

		Page page = new Page(gasCamchange.getPage(), gasCamchange.getLimit());
		LambdaQueryWrapper<GasCamchangeEntity> queryWrapper = Wrappers.lambdaQuery();
		// 查询条件示例
		if (!StringUtils.isEmpty(createTimeStart)) {
			queryWrapper.ge(GasCamchangeEntity::getCreateTime, sdf.parse(createTimeStart + " 00:00:00"));
		}
		if (!StringUtils.isEmpty(createTimeEnd)) {
			queryWrapper.le(GasCamchangeEntity::getCreateTime, sdf.parse(createTimeEnd + " 23:59:59"));
		}

		if (!StringUtils.isEmpty(taxorgcode)) {
			queryWrapper.eq(GasCamchangeEntity::getHandleTaxorgcode, taxorgcode);

		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapper.eq(GasCamchangeEntity::getHandleTaxorgcode, currentDeptId);
			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局
				queryWrapper.like(GasCamchangeEntity::getHandleTaxorgcode, currentDeptId.substring(0, 5));
			} else {
				// 省局
			}
		}

		if (TsBqUtils.isNotNull(stationinfoIdList)) {
			queryWrapper.in(GasCamchangeEntity::getMessageGroupid, stationinfoIdList);
		}

		queryWrapper.isNotNull(GasCamchangeEntity::getHandleType);

		IPage<GasCamchangeEntity> iPage = gasCamchangeService.page(page, queryWrapper);
		List<GasCamchangeEntity> records = iPage.getRecords();
		for (GasCamchangeEntity camchangeEntity : records) {
			String messageGroupid = camchangeEntity.getMessageGroupid();
			GasStationinfoEntity stationinfoEntity = gasStationinfoService.getById(messageGroupid);
			if (TsBqUtils.isNotNull(stationinfoEntity)) {
				String name = stationinfoEntity.getName();
				camchangeEntity.setStationinfoName(name);
				
				String taxpayerCode = stationinfoEntity.getTaxpayerCode();
				camchangeEntity.setTaxpayerCode(taxpayerCode);
			}

		}

		return DataResult.success(iPage);
	}

	public String removeFirstAndLastChar(String s) {
		if (s.length() <= 2) {
			return ""; // 如果字符串长度小于等于2，则返回空字符串
		}
		String str = s.substring(1, s.length() - 1);
		String replaceAll = str.replaceAll("\\\\", "");
		return replaceAll;

	}

	private String sign(String url, Map<String, Object> parameter, String pass) throws UnsupportedEncodingException {
		if (!parameter.isEmpty()) {
			url = url + "?";
			for (String key : parameter.keySet()) {
				url = url + key + "=" + parameter.get(key) + "&";
			}
			url = url.substring(0, url.length() - 1);
		}

		String encrypt = MD5Utils.encrypt(pass);
		byte[] hmacSHA256 = HmacSha256Utils.hmacSHA256(url, encrypt);
		byte[] encodedBytes = Base64.getEncoder().encode(hmacSHA256);
		String encodedString = URLEncoder.encode(new String(encodedBytes), "UTF-8");

		return encodedString;
	}

	public static String makeSign(String url, String appuser, String apppass) throws Exception {
		// 1. 计算平台密码的MD5值作为key
		String key = md5(apppass);
		System.out.println("key:" + key);

		// 2. 使用HmacSHA256算法计算签名
		String signatureSHA = hmacSha256(url, key);
		System.out.println("signatureSHA:" + signatureSHA);

		// 3. 将签名进行Base64编码
		String signatureBase64 = Base64.getEncoder().encodeToString(signatureSHA.getBytes(StandardCharsets.UTF_8));
		System.out.println("signatureBase64:" + signatureBase64);

		// 4. 对Base64编码结果进行URL编码
		String signURI = URLEncoder.encode(signatureBase64, "UTF-8");
		System.out.println("signatureBaseURI:" + signURI);

		return signURI;
	}

	private static String md5(String input) throws Exception {
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
		StringBuilder hexString = new StringBuilder();

		for (byte b : hash) {
			String hex = Integer.toHexString(0xff & b);
			if (hex.length() == 1)
				hexString.append('0');
			hexString.append(hex);
		}

		return hexString.toString();
	}

	private static String hmacSha256(String data, String key) throws Exception {
		Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
		SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
		sha256_HMAC.init(secret_key);

		byte[] hash = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
		StringBuilder hexString = new StringBuilder();

		for (byte b : hash) {
			String hex = Integer.toHexString(0xff & b);
			if (hex.length() == 1)
				hexString.append('0');
			hexString.append(hex);
		}

		return hexString.toString();
	}
}
